#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/7 9:51
# @Author  : leon yan
# @Site    : 
# @File    : qpulsethread.py
# @Software: PyCharm
import datetime
import threading
import time
from datetime import date
from threading import Lock
import Globalist as gl
from lib.qsqledit import NewProductLogDB, ReadTodayDB, UpdateDB2
from PyQt5.QtCore import QObject, pyqtSignal


def save2LogData(lst):
    loginUser = gl.global_var["userVar"]["LoginUserName"]
    saveList = [lst[0], lst[1], lst[2], lst[3], lst[4], lst[5], lst[6], loginUser]
    NewProductLogDB([saveList])


def update2DbData(dbName, dctUpLst, id):
    loginUser = gl.global_var["userVar"]["LoginUserName"]
    dctUpLst.update({"Operator": loginUser})
    UpdateDB2(dbName, dctUpLst, id)


class QPollThread(QObject):
    bPulse = pyqtSignal()

    def __init__(self):
        super().__init__()
        # init a thread lock
        self.regs_lock = Lock()
        self.counter = 0
        self.todayLogId = None
        self.todayInitPower = 0.0
        self.todayInitAmount = 0.0

    '''
    '''

    def polling_thread(self):
        # polling loop
        while True:
            self.bPulse.emit()
            time.sleep(0.5)

    def polling_thread2(self):
        # polling loop
        while True:
            self.doSomething()
            time.sleep(1.0)

    def doSomething(self):
        gl.global_var["monitorVar"]["PowerTime"] += 1
        if gl.global_var["statusVar"]["bRunning"]:
            gl.global_var["monitorVar"]["WorkTime"] += 1
        if gl.global_var["statusVar"]["bAlarm"]:
            gl.global_var["monitorVar"]["AlarmTime"] += 1

        '''total time'''
        aa1 = gl.global_var["monitorVar"]["WorkTime"] / gl.global_var["monitorVar"]["PowerTime"]
        aa2 = gl.global_var["monitorVar"]["AlarmTime"] / gl.global_var["monitorVar"]["PowerTime"]
        aa3 = 100-aa1-aa2

        gl.global_var["chartMonitor"]["timeMonitor"][0][1] = round(aa1, 1)
        gl.global_var["chartMonitor"]["timeMonitor"][1][1] = round(aa2, 1)
        gl.global_var["chartMonitor"]["timeMonitor"][2][1] = round(aa3, 1)

        # currentDate = datetime.datetime.strftime(datetime.datetime.now(), '%Y/%m/%d')
        currentDate = datetime.datetime.now().date()
        self.counter += 1
        if self.counter > 5:
            gl.global_config['working']["PowerTime"] = gl.global_var["monitorVar"]["PowerTime"]
            gl.global_config['working']["WorkTime"] = gl.global_var["monitorVar"]["WorkTime"]
            gl.global_config['working']["AlarmTime"] = gl.global_var["monitorVar"]["AlarmTime"]
            gl.global_config.write()

            '''记录耗电量'''
            '''new DB'''
            a1 = float(gl.global_var["monitorVar"]["TotalPower"])
            strWhere = "LogTime = DateValue(#" + str(currentDate) + "#)"  # access 数据库日期搜索方式
            ret = ReadTodayDB("ProductLog", strWhere)
            if not ret:
                lst = [currentDate, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ""]
                save2LogData(lst)
            else:
                self.todayLogId = ret[0][0]
                self.todayInitPower = ret[0][2]
                self.todayInitAmount = ret[0][4]
                gl.global_var["monitorVar"]["TodayPower"] = ret[0][6]
                gl.global_var["monitorVar"]["TodayAmount"] = ret[0][7]

                '''update'''
                updateDict = {}
                if a1 > 0.0:
                    if self.todayInitPower == 0.0:
                        updateDict["TodayInitPower"] = str(round(a1, 1))
                    else:
                        updateDict["TotalPower"] = str(round(a1, 1))
                        updateDict["DatePower"] = str(round(a1 - self.todayInitPower, 1))

                a2 = float(gl.global_var["monitorVar"]["TotalAmount"])
                # print(type(a2))
                if a2 > 0.0:
                    if self.todayInitAmount == 0.0:
                        updateDict["TodayInitAmount"] = round(a2, 1)
                    else:
                        updateDict["TotalAmount"] = round(a2, 1)
                        updateDict["DateAmount"] = str(round(a1 - self.todayInitAmount, 1))
                # print(updateDict)
                if updateDict:
                    update2DbData("ProductLog", updateDict, {"id": self.todayLogId})

            self.counter = 0


if __name__ == '__main__':
    # while True:
    tpj = QPollThread()
    theThread1 = threading.Thread(target=tpj.polling_thread)
    theThread1.daemon = True
    theThread1.start()
    while True:
        pass
